package com.hz.house.utils;

import java.security.MessageDigest;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

public class EncodeUtils {
    private static final String APP_ID = "dyapikey:2020-2-23";
    private static final String APP_KEY = "7b812403bc7c7fcba7e4c2ca85b8d5e5";

    public static boolean checkSign(Map<String, Object> param){
        String app_id = (String) param.get("app_id");
        if (!APP_ID.equals(app_id)){
            return false;
        }
        String sign = (String) param.get("sign");
        Map<String, Object> signParam = new TreeMap<>();
        for (Map.Entry<String, Object> entry : param.entrySet()){
            if ("sign".equals(entry.getKey()))
                continue;
            signParam.put(entry.getKey(), entry.getValue());
        }
        String newSign = encode(signParam);
        return newSign.equals(sign);
    }

    public static void main(String[] args) {
        Map<String, Object> signParam = new TreeMap<>();
        signParam.put("encode_number", "028850000");
        signParam.put("app_id", APP_ID);
        String sign = encode(signParam);
        System.out.println(sign);
    }

    public static String encode(Map<String, Object> param){
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, Object> entry: param.entrySet()){
            builder.append("&").append(entry.getKey()).append("=").append(Objects.isNull(entry.getValue()) ? "": entry.getValue());
        }
        builder.append(APP_KEY);
        return MD532(builder.toString());
    }

    private static String MD532(String source){
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] md5Bytes = md5.digest(source.getBytes());
            StringBuffer hexValue = new StringBuffer();
            for (int i = 0; i < md5Bytes.length; i++) {
                int val = ((int) md5Bytes[i]) & 0xff;
                if (val < 16)
                    hexValue.append("0");
                hexValue.append(Integer.toHexString(val));
            }
            source = hexValue.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return source;
    }
}
